package com.example.demo.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class PasswordUtils {
    public static String encrypt(String password){
        String salt= UUID.randomUUID().toString().replace("-","");
        String finalPassword=DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+"$"+finalPassword;
    }

    public static boolean decrypt(String password,String dbPassword){
        if(!StringUtils.hasLength(password)||!StringUtils.hasLength(dbPassword)||dbPassword.length()!=65){
            return false;
        }
        String[] arr=dbPassword.split("\\$");
        if(arr.length!=2){
            return false;
        }
        String salt=arr[0];
        String dbFinalPassword=arr[1];
        String FinalPassword=DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        if(FinalPassword.equals(dbFinalPassword)){
            return true;
        }
        return false;
    }
}
